package com.huiztech.maystall.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.R.color;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.huewu.pla.lib.extra.MultiColumnPullToRefreshListView;
import com.huewu.pla.lib.extra.MultiColumnPullToRefreshListView.OnRefreshListener;
import com.huewu.pla.lib.internal.PLA_AbsListView;
import com.huewu.pla.lib.internal.PLA_AbsListView.OnScrollListener;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener;
import com.huiztech.maystall.adapter.WaterfallAdapter;
import com.huiztech.maystall.mvc.Controller;
import com.huiztech.maystall.mvc.MaystallView;

public class MainActivity extends BaseActivity implements OnRefreshListener, OnScrollListener {

    private ViewPager viewPager; // 滑动组件
    private List<ImageView> imageViews; // 广告图片
    private int[] imageResId; // 图片ID
    private List<View> dots; // 图片标题正文的那些点
    private int currentItem = 0; // 当前图片的索引号
    private ScheduledExecutorService scheduledExecutorService;

    private MultiColumnPullToRefreshListView waterfallView;// 瀑布流组件
    private boolean flag = true;
    private List<Map<String, Object>> productList;
    private List<Map<String, Object>> adList;
    private FrameLayout adFrameLayout;
    private WaterfallAdapter adapter;

    private Button newBtn, fieryBtn;

    private Controller controller;
    private MaystallView view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = new MaystallView();
        controller = new Controller(view, this);
        productList = new ArrayList<Map<String, Object>>();
        adList = new ArrayList<Map<String, Object>>();

        getImageData();

        adFrameLayout = (FrameLayout) findViewById(R.id.main_ad_layout);

        dots = new ArrayList<View>();
        dots.add(findViewById(R.id.v_dot0));
        dots.add(findViewById(R.id.v_dot1));
        dots.add(findViewById(R.id.v_dot2));
        dots.add(findViewById(R.id.v_dot3));

        viewPager = (ViewPager) findViewById(R.id.vp);
        viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
        // 设置一个监听器，当ViewPager中的页面改变时调用
        viewPager.setOnPageChangeListener(new MyPageChangeListener());

        // 瀑布流
        waterfallView = (MultiColumnPullToRefreshListView) findViewById(R.id.list);
        adapter = new WaterfallAdapter(productList, this);
        waterfallView.setAdapter(adapter);
        waterfallView.setOnRefreshListener(this);
        waterfallView.setOnScrollListener(this);

        newBtn = (Button) findViewById(R.id.main_new_btn);
        fieryBtn = (Button) findViewById(R.id.main_fiery_btn);

        newBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                newBtn.setTextColor(getResources().getColorStateList(R.color.white)); // 最新按钮颜色变白
                newBtn.setBackgroundResource(R.drawable.home_newbtn_bg);// 最新按钮填充背景

                fieryBtn.setTextColor(getResources().getColorStateList(R.color.main_btn_color));// 最热按钮变色
                // 最热按钮背景透明
                fieryBtn.setBackgroundColor(R.color.touming);
                fieryBtn.setBackgroundDrawable(null);

                productList = controller.getNewProduct(0);
                adapter = new WaterfallAdapter(productList, MainActivity.this);
                waterfallView.setAdapter(adapter);
            }
        });

        fieryBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                fieryBtn.setTextColor(getResources().getColorStateList(R.color.white));
                fieryBtn.setBackgroundResource(R.drawable.home_newbtn_bg);

                newBtn.setTextColor(getResources().getColorStateList(R.color.main_btn_color));
                newBtn.setBackgroundColor(R.color.touming);
                newBtn.setBackgroundDrawable(null);

                productList = controller.getFireyProduct(0);
                adapter = new WaterfallAdapter(productList, MainActivity.this);
                waterfallView.setAdapter(adapter);
            }
        });

    }

    // 瀑布流刷新事件
    @Override
    public void onRefresh() {
        // 刷新之后
//        new Handler().postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
                waterfallView.onRefreshComplete();
//            }
//
//        }, 2000);
        // 刷新之后调用
    }

    // 瀑布流滑动事件
    @Override
    public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (firstVisibleItem == 0) {
            flag = true;
        }
    }

    // 取得广告数据
    private void getImageData() {
        imageViews = new ArrayList<ImageView>();
        adList = controller.getAdDetail();

        // 需要显示的图片
        for (int i = 0; i < adList.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource((Integer) adList.get(i).get("image"));
            imageView.setScaleType(ScaleType.CENTER_CROP);
            imageViews.add(imageView);
        }

        productList = controller.getNewProduct(0);
    }

    @Override
    protected void onStart() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每三秒钟切换一次图片显示
        scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 3, TimeUnit.SECONDS);
        super.onStart();
    }

    @Override
    protected void onStop() {
        // 当Activity不可见的时候停止切换
        scheduledExecutorService.shutdown();
        super.onStop();
    }

    // 切换当前显示的图片
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
        };
    };

    /**
     * 换行切换任务
     * 
     */
    private class ScrollTask implements Runnable {

        public void run() {
            synchronized (viewPager) {
                System.out.println("currentItem: " + currentItem);
                currentItem = (currentItem + 1) % imageViews.size();
                handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
            }
        }

    }

    /**
     * 当ViewPager中页面的状态发生改变时调用
     * 
     */
    private class MyPageChangeListener implements OnPageChangeListener {
        private int oldPosition = 0;

        public void onPageSelected(int position) {
            currentItem = position;
            dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dots.get(position).setBackgroundResource(R.drawable.dot_focused);
            oldPosition = position;
        }

        public void onPageScrollStateChanged(int arg0) {

        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }
    }

    /**
     * 填充ViewPager页面的适配器
     * 
     */
    private class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return adList.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(imageViews.get(arg1));
            return imageViews.get(arg1);
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }
    }

}
